<template>
  <div v-loading="loading_async" class="app_conn" element-loading-text="加载中...">
    <div class="mag_bg">
      <div class="set_top">
        <el-form
          v-if="getYunxkCfigObj"
          ref="inviteCodeForm"
          :model="getYunxkCfigObj"
          label-width="auto"
          class="box-content"
          label-position="left"
          @click="$event.preventDefault()"
          @submit.prevent="() => {}"
        >
          <el-form-item class="form_item" prop="enabled">
            <template #label>
              <div class="form_item_label">
                <span class="name">开启用友U8<sup>+</sup>接口</span>
                <span class="tips">
                  <span>
                    是否启用用友U8<sup>+</sup>接口同步数据，开启后：支持同步；关闭后：所有接口禁用；
                  </span>
                </span>
              </div>
            </template>
            <div style="display: flex; justify-content: flex-end; margin-right: 46px; gap: 10px">
              <el-switch
                v-if="getYunxkCfigObj"
                v-model="getYunxkCfigObj.enabled"
                @change="changeacctId()"
              />
              <span v-if="getYunxkCfigObj?.enabled">开启</span>
              <span v-if="!getYunxkCfigObj?.enabled">关闭</span>
            </div>
          </el-form-item>
          <el-form-item class="form_item">
            <template #label>
              <div class="form_item_label">
                <span class="name">调用方ID(From_account)</span>
              </div>
            </template>
            <div class="normal_tip">
              <el-input
                v-if="!is_show1 && getYunxkCfigObj.fromAccount"
                placeholder="请输入调用方ID"
                disabled
                :value="maskString(getYunxkCfigObj.fromAccount)"
                class="input_width"
              />
              <el-input
                v-if="is_show1 || !getYunxkCfigObj.fromAccount"
                v-model.trim="getYunxkCfigObj.fromAccount"
                placeholder="请输入调用方ID"
                :disabled="!is_edit1"
                class="input_width"
              />
              <el-space style="width: 100px" :size="0" :spacer="spacer">
                <el-tooltip
                  v-if="!is_show1 && getYunxkCfigObj.fromAccount"
                  effect="dark"
                  content="查看"
                  placement="left"
                >
                  <el-icon style="cursor: pointer" @click="is_show1 = !is_show1">
                    <Hide />
                  </el-icon>
                </el-tooltip>
                <el-tooltip
                  v-if="(is_show1 && getYunxkCfigObj.fromAccount) || !getYunxkCfigObj.fromAccount"
                  effect="dark"
                  content="隐藏"
                  placement="left"
                >
                  <el-icon style="cursor: pointer" @click="is_show1 = !is_show1">
                    <View />
                  </el-icon>
                </el-tooltip>
                <span v-if="!ctrlShow" style="color: #c0c4cc; cursor: not-allowed"> 编辑 </span>
                <h-link v-if="!is_edit1 && ctrlShow" @click="editShow(1)"> 编辑 </h-link>
                <h-link
                  v-if="is_edit1"
                  @click="changeacctId(), (is_edit1 = false), (is_show1 = false)"
                >
                  完成
                </h-link>
                <h-link v-if="is_edit1" @click=";(is_edit1 = false), (is_show1 = false)">
                  取消
                </h-link>
              </el-space>
            </div>
          </el-form-item>
          <el-form-item class="form_item">
            <template #label>
              <div class="form_item_label">
                <span class="name">提供方ID(To_account)</span>
              </div>
            </template>
            <div class="normal_tip">
              <el-input
                v-if="!is_show4 && getYunxkCfigObj.toAccount"
                placeholder="请输入提供方ID"
                disabled
                :value="maskString(getYunxkCfigObj.toAccount)"
                class="input_width"
              />
              <el-input
                v-if="is_show4 || !getYunxkCfigObj.toAccount"
                v-model.trim="getYunxkCfigObj.toAccount"
                placeholder="请输入提供方ID"
                :disabled="!is_edit4"
                class="input_width"
              />
              <el-space style="width: 100px" :size="0" :spacer="spacer">
                <el-tooltip
                  v-if="!is_show4 && getYunxkCfigObj.toAccount"
                  effect="dark"
                  content="查看"
                  placement="left"
                >
                  <el-icon style="cursor: pointer" @click="is_show4 = !is_show4">
                    <Hide />
                  </el-icon>
                </el-tooltip>
                <el-tooltip
                  v-if="(is_show4 && getYunxkCfigObj.toAccount) || !getYunxkCfigObj.toAccount"
                  effect="dark"
                  content="隐藏"
                  placement="left"
                >
                  <el-icon style="cursor: pointer" @click="is_show4 = !is_show4">
                    <View />
                  </el-icon>
                </el-tooltip>
                <span v-if="!ctrlShow" style="color: #c0c4cc; cursor: not-allowed"> 编辑 </span>
                <span
                  v-if="!is_edit4 && ctrlShow"
                  style="color: #007cff; cursor: pointer"
                  @click="editShow(4)"
                >
                  编辑
                </span>
                <span
                  v-if="is_edit4"
                  style="color: #007cff; cursor: pointer"
                  @click="changeacctId(), (is_edit4 = false), (is_show4 = false)"
                >
                  完成
                </span>
                <span
                  v-if="is_edit4"
                  style="color: #007cff; cursor: pointer"
                  @click=";(is_edit4 = false), (is_show4 = false)"
                >
                  取消
                </span>
              </el-space>
            </div>
          </el-form-item>
          <el-form-item class="form_item">
            <template #label>
              <div class="form_item_label">
                <span class="name">应用条码(AppKey)</span>
              </div>
            </template>
            <div class="normal_tip">
              <el-input
                v-if="!is_show2 && getYunxkCfigObj.appKey"
                placeholder="请输入应用密钥"
                disabled
                :value="maskString(getYunxkCfigObj.appKey)"
                class="input_width"
              />
              <el-input
                v-if="is_show2 || !getYunxkCfigObj.appKey"
                v-model.trim="getYunxkCfigObj.appKey"
                placeholder="请输入应用条码"
                :disabled="!is_edit2"
                class="input_width"
              />
              <el-space style="width: 100px" :size="0" :spacer="spacer">
                <el-tooltip
                  v-if="!is_show2 && getYunxkCfigObj.appKey"
                  effect="dark"
                  content="查看"
                  placement="left"
                >
                  <el-icon style="cursor: pointer" @click="is_show2 = !is_show2">
                    <Hide />
                  </el-icon>
                </el-tooltip>
                <el-tooltip
                  v-if="(is_show2 && getYunxkCfigObj.appKey) || !getYunxkCfigObj.appKey"
                  effect="dark"
                  content="隐藏"
                  placement="left"
                >
                  <el-icon style="cursor: pointer" @click="is_show2 = !is_show2">
                    <View />
                  </el-icon>
                </el-tooltip>
                <span v-if="!ctrlShow" style="color: #c0c4cc; cursor: not-allowed"> 编辑 </span>
                <span
                  v-if="!is_edit2 && ctrlShow"
                  style="color: #007cff; cursor: pointer"
                  @click="editShow(2)"
                >
                  编辑
                </span>
                <span
                  v-if="is_edit2"
                  style="color: #007cff; cursor: pointer"
                  @click="changeacctId(), (is_edit2 = false), (is_show2 = false)"
                >
                  完成
                </span>
                <span
                  v-if="is_edit2"
                  style="color: #007cff; cursor: pointer"
                  @click=";(is_edit2 = false), (is_show2 = false)"
                >
                  取消
                </span>
              </el-space>
            </div>
          </el-form-item>
          <el-form-item class="form_item">
            <template #label>
              <div class="form_item_label">
                <span class="name">应用密钥(AppSecret)</span>
              </div>
            </template>
            <div class="normal_tip">
              <el-input
                v-if="!is_show3 && getYunxkCfigObj.appSecret"
                placeholder="请输入应用密钥"
                disabled
                :value="maskString(getYunxkCfigObj.appSecret)"
                class="input_width"
              />

              <el-input
                v-if="is_show3 || !getYunxkCfigObj.appSecret"
                v-model.trim="getYunxkCfigObj.appSecret"
                placeholder="请输入应用密钥"
                :disabled="!is_edit3"
                class="input_width"
              />
              <el-space style="width: 100px" :size="0" :spacer="spacer">
                <el-tooltip
                  v-if="!is_show3 && getYunxkCfigObj.appSecret"
                  effect="dark"
                  content="查看"
                  placement="left"
                >
                  <el-icon style="cursor: pointer" @click="is_show3 = !is_show3">
                    <Hide />
                  </el-icon>
                </el-tooltip>
                <el-tooltip
                  v-if="(is_show3 && getYunxkCfigObj.appSecret) || !getYunxkCfigObj.appSecret"
                  effect="dark"
                  content="隐藏"
                  placement="left"
                >
                  <el-icon style="cursor: pointer" @click="is_show3 = !is_show3">
                    <View />
                  </el-icon>
                </el-tooltip>
                <span v-if="!ctrlShow" style="color: #c0c4cc; cursor: not-allowed"> 编辑 </span>
                <span
                  v-if="!is_edit3 && ctrlShow"
                  style="color: #007cff; cursor: pointer"
                  @click="editShow(3)"
                >
                  编辑
                </span>
                <span
                  v-if="is_edit3"
                  style="color: #007cff; cursor: pointer"
                  @click="changeacctId(), (is_edit3 = false), (is_show3 = false)"
                >
                  完成
                </span>
                <span
                  v-if="is_edit3"
                  style="color: #007cff; cursor: pointer"
                  @click=";(is_edit3 = false), (is_show3 = false)"
                >
                  取消
                </span>
              </el-space>
            </div>
          </el-form-item>
          <el-form-item class="form_item">
            <template #label>
              <div class="form_item_label">
                <span class="name">数据库域名或IP(用于连接数据库服务)</span>
              </div>
            </template>
            <div class="normal_tip">
              <el-input
                v-if="!is_show5 && getYunxkCfigObj.url"
                placeholder="请输入接口域名或IP"
                disabled
                :value="maskString(getYunxkCfigObj.url)"
                class="input_width"
              />

              <el-input
                v-if="is_show5 || !getYunxkCfigObj.url"
                v-model.trim="getYunxkCfigObj.url"
                placeholder="请输入接口域名或IP"
                :disabled="!is_edit5"
                class="input_width"
              />
              <el-space style="width: 100px" :size="0" :spacer="spacer">
                <el-tooltip
                  v-if="!is_show5 && getYunxkCfigObj.url"
                  effect="dark"
                  content="查看"
                  placement="left"
                >
                  <el-icon style="cursor: pointer" @click="is_show5 = !is_show5">
                    <Hide />
                  </el-icon>
                </el-tooltip>
                <el-tooltip
                  v-if="(is_show5 && getYunxkCfigObj.url) || !getYunxkCfigObj.url"
                  effect="dark"
                  content="隐藏"
                  placement="left"
                >
                  <el-icon style="cursor: pointer" @click="is_show5 = !is_show5">
                    <View />
                  </el-icon>
                </el-tooltip>
                <span v-if="!ctrlShow" style="color: #c0c4cc; cursor: not-allowed"> 编辑 </span>
                <span
                  v-if="!is_edit5 && ctrlShow"
                  style="color: #007cff; cursor: pointer"
                  @click="editShow(5)"
                >
                  编辑
                </span>
                <span
                  v-if="is_edit5"
                  style="color: #007cff; cursor: pointer"
                  @click="changeacctId(), (is_edit5 = false), (is_show5 = false)"
                >
                  完成
                </span>
                <span
                  v-if="is_edit5"
                  style="color: #007cff; cursor: pointer"
                  @click=";(is_edit5 = false), (is_show5 = false)"
                >
                  取消
                </span>
              </el-space>
            </div>
          </el-form-item>
          <!-- <div class="form_item_footer">
                        <HPlainButton type="primary" >保存</HPlainButton>
                    </div> -->
        </el-form>
        <div class="set_top_right">
          <div class="set_top_right_item">
            <div class="set_tag_item version">
              <div class="content">
                <p>版本</p>
                <p>V20240701.1.0</p>
              </div>
            </div>
            <div class="set_tag_item">
              <div class="content">
                <p>适用于</p>
                <p>用友U8<sup>+</sup></p>
              </div>
            </div>
          </div>
          <!-- <div class="set_top_right_item">
                        <div class="set_tag_item">
                            <p>配置包下载</p>
                            <p @click="downLoad" class="xy_main_btn">用友配置包</p>
                        </div>
                        <div class="set_tag_item">
                            <p>帮助</p>
                            <p class="xy_main_btn" @click="downLoadPDF"><el-icon color="#007cff">
                                    <Reading />
                                </el-icon>使用说明</p>
                        </div>
                    </div> -->
        </div>
      </div>
    </div>
    <div class="mag_bg" style="flex: 1">
      <div class="title_top">对接列表</div>
      <div class="table_box">
        <div class="table">
          <el-table :border="true" height="100%" stripe resizable :data="tableDataList">
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <!-- 序号 -->
            <el-table-column label="序号" type="index" width="50" :align="'center'" fixed="left" />
            <!-- 名称 -->
            <el-table-column show-overflow-tooltip label="接口名称" prop="name" min-width="140" />
            <!-- <el-table-column show-overflow-tooltip label="接口同步情况" align="center" width="100">
                        <template v-slot="i">
                            <span style="display: flex;align-items: center;justify-content: center;">
                                <HStatus v-if="i.row.type == 3 || i.row.type == 1 || i.row.type == 7" type="warning">空闲中
                                </HStatus>
                                <HStatus v-else-if="i.row.type == 4 || i.row.type == 6">同步中</HStatus>
                                <HStatus type="info" v-else-if="i.row.type == 5">禁用</HStatus>
                                <HStatus type="error" v-else>异常</HStatus>
                            </span>
                        </template>
                    </el-table-column> -->
            <el-table-column show-overflow-tooltip label="对接方向" prop="" width="80">
              <template #default="i">
                <span v-if="[7, 8, 9].includes(i.row.type)">反写</span>
                <span v-else>同步</span>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="数据类型" prop="userName" min-width="120">
              <template #default="i">
                {{
                  [5, 6, 7].includes(i.row.type)
                    ? '出库单据'
                    : i.row.type == 23
                    ? '条码同步'
                    : '基础资料'
                }}
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="接口状态"
              prop="userName"
              :align="'center'"
              width="80"
              fixed="right"
            >
              <template #default="i">
                <div class="flex_justify_center">
                  <HStatus v-if="i.row.status || !ctrlShow" type="info">禁用</HStatus>
                  <HStatus v-else>启用</HStatus>
                </div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" prop="userName" width="200">
              <template #default="i">
                <el-space :size="0" :spacer="spacer">
                  <HLink
                    v-if="ctrlShow && ![4, 23].includes(i.row.type)"
                    @click="popRight(i.row.type)"
                  >
                    设置
                  </HLink>
                  <HLink v-else-if="!ctrlShow && ![4, 23, 6].includes(i.row.type)" disabled>
                    设置
                  </HLink>
                  <HLink v-if="i.row.type == 2 && ctrlShow" @click="asyncTypeShow(i.row.type, 1)">
                    成品同步
                  </HLink>
                  <HLink v-else-if="i.row.type == 2 && !ctrlShow" disabled>成品同步</HLink>
                  <HLink v-if="i.row.type == 2 && ctrlShow" @click="asyncTypeShow(i.row.type, 2)">
                    物料同步
                  </HLink>
                  <HLink v-else-if="i.row.type == 2 && !ctrlShow" disabled>物料同步</HLink>
                  <HLink
                    v-else-if="!(i.row.type == 7) && ctrlShow"
                    @click="asyncTypeShow(i.row.type)"
                  >
                    同步
                  </HLink>
                  <HLink v-else-if="!(i.row.type == 7)" disabled>同步</HLink>
                  <!-- <HLink type="error">禁用</HLink> -->
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 同步数据弹窗 -->
    <h-dialog
      v-model="isBigAsync"
      :width="800"
      title="同步数据"
      :is-close-btn-click-hide-dialog="false"
      @close="onCloseSynchronizationDialog"
    >
      <div class="synchronization-progress-wrapper">
        <el-progress
          v-if="dataReturned ? dataReturned.end === false : true"
          :stroke-width="10"
          type="circle"
          :percentage="syncProgress"
          color="#00c0c0"
          class="synchronization-progress"
        >
          <div class="progress-content">
            <div class="num">{{ syncProgress.toFixed(2) }}%</div>
            <div class="tip">正在同步数据，请稍等...&nbsp;...</div>
          </div>
        </el-progress>
        <div
          v-if="dataReturned && dataReturned.end && msgHtml.length === 0"
          class="success-wrapper"
        >
          <div class="circle">
            <i class="iconfont icon-dagou"></i>
          </div>
          <div class="tip">数据同步成功</div>
        </div>
        <div v-if="dataReturned && dataReturned.end && msgHtml.length > 0" class="fail-wrapper">
          <div class="circle-bg">
            <div class="circle">
              <i class="iconfont icon-guanbi"></i>
            </div>
          </div>
          <div ref="msgContentBoxs" class="msg-wrapper">
            <span v-for="(item, index) in msgHtml" :key="index" v-html="item"></span>
          </div>
        </div>
      </div>

      <template #footer>
        <h-button is-modal @click="onCloseSynchronizationDialog">关闭</h-button>
      </template>
    </h-dialog>

    <h-drawer
      v-model="popRightDialog"
      :width="60"
      :loading="
        getSaleWarehouseOutSetLoading ||
        saleWarehouseOutSetSaveSetLoading ||
        saleWarehouseOutSaveSetAndAsyncLoading
      "
      @close="onPopCancel"
    >
      <template #title>
        <div class="title_el_dra">
          <span class="text">{{ popRightTitle }}</span>
          <i class="iconfont icon-refresh_2" @click="popRight(isType)"></i>
          <div class="tip">
            <div class="dot"></div>
            <div class="text">点击刷新</div>
          </div>
        </div>
      </template>
      <div v-loading="loading" class="pop-dialog" element-loading-text="加载中...">
        <el-form
          ref="formRef"
          label-width="auto"
          style="height: 100%; display: flex; flex-direction: column"
          label-position="left"
        >
          <el-form-item>
            <template #label>
              <span style="width: 8px; color: #f56c6c"></span>
              <span class="label_flex">
                <el-icon>
                  <Tickets />
                </el-icon>
                <span>描述</span>
              </span>
            </template>
            {{ Description_Content }}
          </el-form-item>
          <el-form-item v-if="![1].includes(isType)">
            <template #label>
              <span style="width: 8px; color: #f56c6c"></span>
              <span class="label_flex">
                <el-icon>
                  <Refresh />
                </el-icon>
                {{ [7].includes(isType) ? '反写条件' : '同步条件' }}
              </span>
            </template>
            <span style="color: #007cff">{{ synchronous_Conditions }}</span>
          </el-form-item>
          <!-- 1 -->
          <template v-if="[1].includes(isType)">
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <Iphone />
                  </el-icon>
                  手机为空或不对时补充为
                </span>
              </template>
              <div class="form_item_content">
                <el-input
                  v-model.trim="userCfigVo.customerPhone"
                  placeholder="请输入手机号前7位"
                  style="width: 50%"
                  maxlength="7"
                  @input="userCfigVo.customerPhone = userCfigVo.customerPhone.replace(/\D/g, '')"
                />
                <el-input style="width: 50%" placeholder="随机后四位" disabled />
              </div>
            </el-form-item>
            <el-form-item prop="userAddress">
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <MapLocation />
                  </el-icon>
                  地址为空或不对时补充为
                </span>
              </template>
              <div class="form_item_content" style="align-items: flex-start">
                <SingleAddress ref="singleAddressRef" :address="address" style="width: 50%" />
                <el-input
                  v-model.trim="userCfigVo.customerAddress"
                  style="width: 50%"
                  placeholder="详细地址"
                  clearable
                  maxlength="100"
                />
              </div>
            </el-form-item>
            <div class="divider_line"></div>
            <!-- <div style="
                display: flex;
                justify-content: flex-end;
                flex: 1;
                width: 92%;
                margin-bottom: 10px;
              ">
              <div class="search_box">
                <span>分类搜索:</span>
                <el-input v-model="getUserTypeObj.name" style="flex: 1; width: 100%" clearable @clear="filterMethodUser"
                  @keyup.enter="filterMethodUser" placeholder="公司分类名称"></el-input>
                <div style="display: flex; justify-content: flex-end">
                  <HPlainButton type="primary" @click="filterMethodUser">搜索</HPlainButton>
                </div>
              </div>
            </div> -->
            <div style="display: flex; height: 72%; flex-direction: column">
              <!-- <div class="transfer_left">
                <div class="transfer_header">
                  <el-checkbox v-model="leftObj.checkAll"
                    :disabled="goodsList.filter((o) => !arrTypeIds.includes(o.code)).length == 0"
                    :indeterminate="leftObj.isIndeterminate" @change="handleCheckAllChange">
                    <span class="tip">已选</span>
                  </el-checkbox>
                  <span class="total_num">当前页:{{
    (leftObj.leftChack.length || 0) +
    '/' +
    (goodsList.filter((o) => !arrTypeIds.includes(o.code)).length || 0)
  }}</span>
                </div>
                <div class="transfer_body user_type">
                  <el-empty description="暂无数据"
                    v-if="goodsList.filter((o) => !arrTypeIds.includes(o.code)).length == 0" />
                  <el-checkbox-group v-model="leftObj.leftChack" v-else @change="handleCheckedCitiesChange"
                    class="checkbox-group user_type">
                    <div v-for="item in goodsList" :key="item.code">
                      <el-checkbox v-show="!arrTypeIds.includes(item.code)" :disabled="item.disabled" :key="item.code"
                        :label="item.name" :value="item.code">
                        <span class="lable_text">{{ item.name }}</span>
                      </el-checkbox>
                    </div>
                  </el-checkbox-group>
                </div>
                <div class="transfer_footer">
                  <el-pagination hide-on-single-page :pager-count="5" @current-change="changePageFun($event)"
                    :default-page-size="getUserTypeObj.limit" layout="prev, pager, next" :total="total" />
                </div>
              </div>
              <div class="centre_box">
                <el-button :icon="ArrowLeft" class="btn_cen" type="primary" :disabled="rightObj.rightChack.length == 0"
                  @click="ArrowRightFun"></el-button>
                <el-button :icon="ArrowRight" @click="ArrowLeftFun()" class="btn_cen" type="primary"
                  :disabled="leftObj.leftChack.length == 0"></el-button>
              </div>
              <div class="transfer_right">
                <div class="transfer_header">
                  <el-checkbox v-model="rightObj.checkAllright" :indeterminate="rightObj.isIndeterminateright"
                    :disabled="userCfigVo.customerTypeVos.length == 0" @change="handleCheckAllChangeright">
                    <span class="tip">已选</span>
                  </el-checkbox>
                  <span class="total_num">总数:{{
    (rightObj.rightChack.length || 0) +
    '/' +
    (userCfigVo.customerTypeVos.length || 0)
  }}</span>
                </div>
                <div class="transfer_body user_type">
                  <el-empty description="暂无数据" v-if="userCfigVo.customerTypeVos.length == 0" />
                  <el-checkbox-group v-model="rightObj.rightChack" v-else @change="handleCheckedCitiesChangeright"
                    class="checkbox-group user_type">
                    <div v-for="item in userCfigVo.customerTypeVos.slice(
    getUserTypeObj.limit * (page - 1),
    getUserTypeObj.limit * page,
  )" :key="item.typeId">
                      <el-checkbox :key="item.typeId" :label="item.type" :value="item.typeId">
                        <span class="lable_text">{{ item.type }}</span>
                      </el-checkbox>
                    </div>
                  </el-checkbox-group>
                </div>
                <div class="transfer_footer">
                  <el-pagination hide-on-single-page :pager-count="5" @current-change="changePageFunright($event)"
                    :default-page-size="getUserTypeObj.limit" layout="prev, pager, next"
                    :total="userCfigVo.customerTypeVos.length" />
                </div>
              </div> -->
              <el-checkbox
                v-if="goodsList.length > 0"
                v-model="userSelectObj.allValue"
                :indeterminate="userSelectObj.isIndeterminate"
                name="type"
                style="margin-left: 22px"
                @change="userSelectObjchangeAll"
              >
                全选
              </el-checkbox>
              <div v-loading="loading_goods" class="goods_type" element-loading-text="加载中...">
                <el-tree
                  ref="treeUserRef"
                  show-checkbox
                  node-key="code"
                  style="max-width: 360px"
                  default-expand-all
                  :data="goodsList"
                  :props="defaultProps"
                  @check="userSelectObjhandleCheckChange"
                />
              </div>
            </div>
          </template>
          <!-- 2 -->
          <template v-if="[2].includes(isType)">
            <!-- <el-form-item>
                            <template #label>
                                <span style="width: 8px;color:#f56c6c">*</span>
                                <span class="label_flex"><el-icon>
                                        <Box />
                                    </el-icon>无分类的物料同步为</span>
                            </template>
      <div class="form_item_content">
        <el-select v-model="goodsCfigVo.goodsTypeId" style="width: 310px;" placeholder="" filterable remote
          reserve-keyword remote-show-suffix :loading="typeLoad" :remote-method="searchTypeSelect">
          <el-option v-for="item in typeOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </div>
      </el-form-item> -->
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <Collection />
                  </el-icon>
                  品牌自动补充为
                </span>
              </template>
              <div class="form_item_content">
                <el-select
                  v-model="goodsCfigVo.goodsBrandId"
                  style="width: 310px"
                  placeholder="请选择品牌"
                  filterable
                  remote
                  reserve-keyword
                  remote-show-suffix
                  :loading="brandLoad"
                  :remote-method="searchBrandSelect"
                >
                  <el-option
                    v-for="item in brandOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </el-form-item>
            <!-- <el-form-item>
                            <template #label>
                                <span style="width: 8px;color:#f56c6c"></span>
                                <span class="label_flex"><el-icon>
                                        <PriceTag />
                                    </el-icon>是否同步价格</span>
                            </template>
                            <el-switch size="small" disabled v-model="goodsCfigVo.syncGoodsPrice" active-text="同步" />
                        </el-form-item> -->

            <div class="tabs_header">
              <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="成品同步" name="first" />
                <el-tab-pane label="物料同步" name="second" />
              </el-tabs>
            </div>
            <template v-if="activeName == 'first'">
              <el-checkbox
                v-if="selectList.length > 0"
                v-model="selectObj.allValue"
                :indeterminate="selectObj.isIndeterminate"
                name="type"
                style="margin-left: 22px"
                @change="changeAll"
              >
                全选
              </el-checkbox>
              <div v-loading="loading_goods" class="goods_type" element-loading-text="加载中...">
                <div v-if="selectList.length === 0" class="no-data-wrapper">
                  <div v-if="errMsgForGetGoodTypeFail" class="main-tip">
                    <i class="iconfont icon-guanbi"></i>
                    <div class="txt">{{ errMsgForGetGoodTypeFail }}</div>
                  </div>
                  <el-empty :image-size="250">
                    <template #description>
                      <div class="sub-tip">暂无数据</div>
                    </template>
                  </el-empty>
                </div>
                <el-tree
                  v-else
                  ref="treeRef"
                  show-checkbox
                  node-key="code"
                  style="max-width: 360px"
                  default-expand-all
                  :data="selectList"
                  :props="defaultProps"
                  @check="handleCheckChange"
                />
              </div>
            </template>
            <template v-if="activeName == 'second'">
              <el-checkbox
                v-if="selectList.length > 0"
                v-model="selectObj.allValue"
                :indeterminate="selectObj.isIndeterminate"
                name="type"
                style="margin-left: 22px"
                @change="changeAll"
              >
                全选
              </el-checkbox>
              <div v-loading="loading_goods" class="goods_type" element-loading-text="加载中...">
                <div v-if="selectList.length === 0" class="no-data-wrapper">
                  <div v-if="errMsgForGetGoodTypeFail" class="main-tip">
                    <i class="iconfont icon-guanbi"></i>
                    <div class="txt">{{ errMsgForGetGoodTypeFail }}</div>
                  </div>
                  <el-empty :image-size="250">
                    <template #description>
                      <div class="sub-tip">暂无数据</div>
                    </template>
                  </el-empty>
                </div>
                <el-tree
                  v-else
                  ref="treeRef"
                  show-checkbox
                  node-key="code"
                  style="max-width: 360px"
                  default-expand-all
                  :data="selectList"
                  :props="defaultProps"
                  @check="handleCheckChange"
                />
              </div>
            </template>
          </template>
          <!-- 12 -->
          <template v-if="[12].includes(isType)">
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <Iphone />
                  </el-icon>
                  网点负责人默认补充为
                </span>
              </template>
              <div class="form_item_content">
                <!-- <el-input style="width: 50%" maxlength="20" placeholder="请输入" v-model="">
                  <template #prepend>
                    <span style="font-size: 12px;">姓名</span>
                  </template></el-input> -->
                <el-input
                  v-model.trim="networkCfigVo.networkPhone"
                  placeholder="请输入"
                  style="width: 50%"
                  maxlength="11"
                  @input="
                    networkCfigVo.networkPhone = networkCfigVo.networkPhone.replace(/\D/g, '')
                  "
                >
                  <template #prepend>
                    <span style="font-size: 12px">手机号</span>
                  </template>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <MapLocation />
                  </el-icon>
                  网点地址为空时默认补充为
                </span>
              </template>
              <div class="form_item_content">
                <SingleAddress ref="singleAddressRef" :address="address" style="width: 50%" />
                <el-input
                  v-model.trim="networkCfigVo.networkAddress"
                  style="width: 50%"
                  placeholder="请输入详细地址"
                  maxlength="100"
                />
              </div>
            </el-form-item>
            <div class="divider_line"></div>
            <el-checkbox
              v-if="networkList.length > 0"
              v-model="networkSelectObj.allValue"
              :indeterminate="networkSelectObj.isIndeterminate"
              name="type"
              style="margin-left: 22px"
              @change="networkSelectObjchangeAll"
            >
              全选
            </el-checkbox>
            <div v-loading="loading_goods" class="goods_type" element-loading-text="加载中...">
              <el-tree
                ref="treeUserRef"
                show-checkbox
                node-key="code"
                style="max-width: 360px"
                default-expand-all
                :data="networkList"
                :props="defaultProps"
                @check="networkSelectObjhandleCheckChange"
              />
            </div>
          </template>
          <!-- 3 -->
          <template v-if="[3].includes(isType)">
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <Iphone />
                  </el-icon>
                  仓库负责人默认补充为
                </span>
              </template>
              <div class="form_item_content">
                <el-input
                  v-model.trim="YunxkStoreCfig.storeUsername"
                  style="width: 50%"
                  maxlength="20"
                  placeholder="请输入"
                >
                  <template #prepend>
                    <span style="font-size: 12px">姓名</span>
                  </template>
                </el-input>
                <el-input
                  v-model.trim="YunxkStoreCfig.storePhone"
                  placeholder="请输入"
                  style="width: 50%"
                  maxlength="11"
                  @input="YunxkStoreCfig.storePhone = YunxkStoreCfig.storePhone.replace(/\D/g, '')"
                >
                  <template #prepend>
                    <span style="font-size: 12px">手机号</span>
                  </template>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <MapLocation />
                  </el-icon>
                  仓库地址为空时默认补充为
                </span>
              </template>
              <div class="form_item_content">
                <SingleAddress ref="singleAddressRef" :address="address" style="width: 50%" />
                <el-input
                  v-model.trim="YunxkStoreCfig.storeAddress"
                  style="width: 50%"
                  placeholder="请输入详细地址"
                  maxlength="100"
                />
              </div>
            </el-form-item>
            <!-- <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c"></span>
                <span class="label_flex"><el-icon>
                    <PriceTag />
                  </el-icon>是否同步库存</span>
              </template>
              <el-switch v-model="YunxkStoreCfig.syncStoreStock" size="small" active-text="同步" />
            </el-form-item> -->
          </template>
          <template v-if="[5].includes(isType)">
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <SoldOut />
                  </el-icon>
                  收货公司若为空时补充为
                </span>
              </template>
              <div class="form_item_content">
                <el-select
                  v-model="OtherStoreCfig.otherOutCustomerId"
                  style="width: 310px"
                  placeholder="请选择"
                >
                  <template #header>
                    <div style="display: flex; gap: 10px; align-items: flex-end">
                      <div style="display: flex; flex-direction: column; gap: 10px; width: 160px">
                        <el-input
                          v-model.trim="dataUserObj.name"
                          clearable
                          placeholder="公司名称"
                          @keyup.enter="selecUserFun"
                          @clear="selecUserFun"
                        />
                      </div>
                      <HPlainButton @click="selecUserFun">搜索</HPlainButton>
                    </div>
                  </template>
                  <el-option
                    v-for="item in dataUserList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </el-form-item>
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <SoldOut />
                  </el-icon>
                  单据类型若为空时补充为
                </span>
              </template>
              <div class="form_item_content">
                <el-select
                  v-model="OtherStoreCfig.otherOutStoreTypeId"
                  style="width: 310px"
                  placeholder="请选择"
                >
                  <template #header>
                    <div style="display: flex; gap: 10px; align-items: flex-end">
                      <div style="display: flex; flex-direction: column; gap: 10px; width: 160px">
                        <el-input
                          v-model.trim="outStoreTypeObj.name"
                          clearable
                          placeholder="单据类型名称"
                          @keyup.enter="outStoreTypePageSelectFun"
                          @clear="outStoreTypePageSelectFun"
                        />
                      </div>
                      <HPlainButton @click="outStoreTypePageSelectFun">搜索</HPlainButton>
                    </div>
                  </template>
                  <el-option
                    v-for="item in outStoreTypeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                    <span style="float: left">{{ item.name }}</span>
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </template>
          <!-- 6 -->
          <template v-if="[6].includes(isType)">
            <!-- <el-form-item>
                            <template #label>
                                <span class="label_flex"><el-icon>
                                        <SoldOut />
                                    </el-icon>出库单类型同步为</span>
                            </template>
  <div class="form_item_content"> <el-select style="width: 310px;" placeholder="若不选，则默认为“销售出库”类型"></el-select>
  </div>
  </el-form-item> -->
            <!-- <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c"></span>
                <span class="label_flex">
                  <el-icon>
                    <PriceTag />
                  </el-icon>
                  是否同步价格
                </span>
              </template>
              <el-switch
                v-model="storeCfigVo.syncSaleOutStorePrice"
                size="small"
                active-text="同步"
              />
            </el-form-item> -->
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c"></span>
                <span class="label_flex">
                  <el-icon>
                    <Timer />
                  </el-icon>
                  同步单据的起止日期
                </span>
              </template>
              <date-range
                :start-date-val="saleWarehouseOutSaveSetVal.saleStoreBillStartDate"
                :end-date-val="saleWarehouseOutSaveSetVal.saleStoreBillEndDate"
                :start-date-width="140"
                :end-date-width="140"
                :date-format="'YYYY-MM-DD HH:mm'"
                @change="handleSaleWarehouseOutStartAndEndDateChange"
              ></date-range>
            </el-form-item>
          </template>
          <!-- 7 -->
          <template v-if="[7].includes(isType)">
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <SoldOut />
                  </el-icon>
                  出库单类型反写为
                </span>
              </template>
              <div class="form_item_content">
                <el-select
                  v-model="reverseWritingCfigVo.otherStoreBillTypeId"
                  style="width: 310px"
                  placeholder="若不选，则默认为“销售出库”类型"
                >
                  <template #header>
                    <div style="display: flex; gap: 10px; align-items: flex-end">
                      <div style="display: flex; flex-direction: column; gap: 10px; width: 160px">
                        <el-input
                          v-model.trim="outStoreData.name"
                          clearable
                          placeholder="单据类型名称"
                          @keyup.enter="getOtherOutStoreBillTypeFun"
                          @clear="getOtherOutStoreBillTypeFun"
                        />
                        <el-input
                          v-model.trim="outStoreData.number"
                          clearable
                          placeholder="单据类型条码"
                          @keyup.enter="getOtherOutStoreBillTypeFun"
                          @clear="getOtherOutStoreBillTypeFun"
                        />
                      </div>
                      <HPlainButton @click="getOtherOutStoreBillTypeFun">搜索</HPlainButton>
                    </div>
                  </template>
                  <el-option
                    v-for="item in OtherOutStoreBillType"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    @click="
                      ;(reverseWritingCfigVo.otherStoreBillType = item.name),
                        (reverseWritingCfigVo.otherStoreBillTypeNumber = item.number)
                    "
                  >
                    <span style="float: left">{{ item.name }}</span>
                    <span style="float: right">
                      {{ item.number }}
                    </span>
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <SoldOut />
                  </el-icon>
                  出库公司若为空时补充为
                </span>
              </template>
              <div class="form_item_content">
                <el-select
                  v-model="reverseWritingCfigVo.otherStoreCustId"
                  style="width: 310px"
                  placeholder="请选择公司下拉"
                >
                  <template #header>
                    <div style="display: flex; gap: 10px; align-items: flex-end">
                      <div style="display: flex; flex-direction: column; gap: 10px; width: 160px">
                        <el-input
                          v-model.trim="getUserData.name"
                          clearable
                          placeholder="公司名称"
                          @keyup.enter="getUserFun"
                          @clear="getUserFun"
                        />
                        <el-input
                          v-model.trim="getUserData.number"
                          clearable
                          placeholder="公司条码"
                          @keyup.enter="getUserFun"
                          @clear="getUserFun"
                        />
                      </div>
                      <HPlainButton @click="getUserFun">搜索</HPlainButton>
                    </div>
                  </template>
                  <el-option
                    v-for="item in getUserObj"
                    :key="item.id"
                    :label="item.fname"
                    :value="item.id"
                    @click="
                      ;(reverseWritingCfigVo.otherStoreCust = item.fname),
                        (reverseWritingCfigVo.otherStoreCustNumber = item.fnumber)
                    "
                  >
                    <span style="float: left">{{ item.fname }}</span>
                    <span style="float: right">{{ item.fnumber }}</span>
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c">*</span>
                <span class="label_flex">
                  <el-icon>
                    <SoldOut />
                  </el-icon>
                  反写到用友的库存状态为
                </span>
              </template>
              <div class="form_item_content">
                <el-select
                  v-model="reverseWritingCfigVo.otherStoreStockStatusId"
                  style="width: 310px"
                  placeholder="请选择用友的库存状态"
                >
                  <el-option
                    v-for="item in getStoreStockStatusObj"
                    :key="item.id"
                    :label="item.fname"
                    :value="item.id"
                    @click="
                      ;(reverseWritingCfigVo.otherStoreStockStatus = item.fname),
                        (reverseWritingCfigVo.otherStoreStockStatusNumber = item.fnumber)
                    "
                  >
                    <span style="float: left">{{ item.fname }}</span>
                    <span style="float: right">{{ item.fnumber }}</span>
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c"></span>
                <span class="label_flex">
                  <el-icon>
                    <SoldOut />
                  </el-icon>
                  反写到用友的单据状态为
                </span>
              </template>
              <div class="form_item_content">
                <el-select
                  v-model="reverseWritingCfigVo.otherStoreBillStatus"
                  disabled
                  style="width: 310px"
                  placeholder="请选择用友的单据状态"
                >
                  <el-option
                    v-for="item in orderStatus"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </el-form-item>
            <!-- <el-form-item>
                            <template #label>
                                <span class="label_flex"><el-icon>
                                        <SoldOut />
                                    </el-icon>反写到用友的库存组织为</span>
                            </template>
                            <div class="form_item_content"> <el-select style="width: 310px;"
                                    v-model="reverseWritingCfigVo.stockOrgId" placeholder="请选择库存组织">
                                    <el-option
                                        @click="reverseWritingCfigVo.stockOrgName = item.name, reverseWritingCfigVo.stockOrgNumber = item.number"
                                        v-for="item in getStockOrgListOp" :key="item.stockOrgId" :label="item.name"
                                        :value="item.stockOrgId"><span style="float: left">{{ item.name }}</span><span
                                            style="float: right;">{{ item.number }}</span></el-option></el-select>
                            </div>
                        </el-form-item> -->

            <el-form-item>
              <template #label>
                <span style="width: 8px; color: #f56c6c"></span>
                <span class="label_flex">
                  <el-icon>
                    <PriceTag />
                  </el-icon>
                  是否反写价格
                </span>
              </template>
              <el-switch
                v-model="reverseWritingCfigVo.syncOtherStoreGoodsPrice"
                size="small"
                active-text="反写"
              />
            </el-form-item>
          </template>
          <template v-if="[8].includes(isType)">
            <el-form-item>
              <template #label>
                <span class="label_flex">
                  <el-icon>
                    <SoldOut />
                  </el-icon>
                  出库单类型同步为
                </span>
              </template>
              <div class="form_item_content">
                <el-select style="width: 310px" placeholder="若不选，则默认为“销售出库”类型" />
              </div>
            </el-form-item>
            <el-form-item>
              <template #label>
                <span class="label_flex">
                  <el-icon>
                    <PriceTag />
                  </el-icon>
                  是否同步价格
                </span>
              </template>
              <el-switch size="small" active-text="同步" />
            </el-form-item>
          </template>
          <el-form-item v-if="[9].includes(isType)">
            <template #label>
              <span class="label_flex">
                <el-icon>
                  <SoldOut />
                </el-icon>
                出库单类型同步为
              </span>
            </template>
            <div class="form_item_content">
              <el-select style="width: 310px" placeholder="若不选，则默认为“销售出库”类型" />
            </div>
          </el-form-item>
          <el-form-item v-if="[9].includes(isType)">
            <template #label>
              <span class="label_flex">
                <el-icon>
                  <PriceTag />
                </el-icon>
                是否同步价格
              </span>
            </template>
            <el-switch size="small" active-text="同步" />
          </el-form-item>
        </el-form>

        <!-- 同步数据弹窗 -->
        <h-dialog
          v-model="isMinAsync"
          :width="800"
          title="同步数据"
          :is-close-btn-click-hide-dialog="false"
          @close="onCloseSynchronizationDialog"
        >
          <div class="synchronization-progress-wrapper">
            <el-progress
              v-if="dataReturned ? dataReturned.end === false : true"
              :stroke-width="10"
              type="circle"
              :percentage="syncProgress"
              color="#00c0c0"
              class="synchronization-progress"
            >
              <div class="progress-content">
                <div class="num"> {{ syncProgress.toFixed(2) }}% </div>
                <div class="tip">正在同步数据，请稍等...&nbsp;...</div>
              </div>
            </el-progress>
            <div
              v-if="dataReturned && dataReturned.end && msgHtml.length === 0"
              class="success-wrapper"
            >
              <div class="circle">
                <i class="iconfont icon-dagou"></i>
              </div>
              <div class="tip">数据同步成功</div>
            </div>
            <div v-if="dataReturned && dataReturned.end && msgHtml.length > 0" class="fail-wrapper">
              <div class="circle-bg">
                <div class="circle">
                  <i class="iconfont icon-guanbi"></i>
                </div>
              </div>
              <div ref="msgContentBoxs" class="msg-wrapper">
                <span v-for="(item, index) in msgHtml" :key="index" v-html="item"></span>
              </div>
            </div>
          </div>

          <template #footer>
            <h-button is-modal @click="onCloseSynchronizationDialog">关闭</h-button>
          </template>
        </h-dialog>
      </div>
      <template #footer>
        <div style="display: flex; gap: 10px">
          <HButton
            v-if="![7].includes(isType)"
            type="primary"
            :disabled="selectList.length === 0 && isType === 2"
            is-modal
            @click="saveAsyncCommit"
          >
            保存并同步
          </HButton>
          <HPlainButton
            :disabled="selectList.length === 0 && isType === 2"
            is-modal
            @click="saveCommit"
          >
            保存设置
          </HPlainButton>
          <HButton is-modal @click="onPopCancel()">关闭</HButton>
        </div>
      </template>
    </h-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, h, onMounted, watch, nextTick } from 'vue'
  import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
  import { initWebSocket, closeWebSocket } from '@/utils/socket'
  import _ from 'lodash'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import {
    getYongyouSetCfig,
    setYongyouSave,
    saveSyncCustomerCfig,
    getyongyouGoodsTypeList,
    getyongyouGoodsCfig,
    saveyongyouGoodsCfig,
    saveWithSyncGoods,
    getYongyouStoreCfig,
    saveYongyouStoreCfig,
    saveSyncStor,
    saveyongyouSyncGoods,
    syncCustomer,
    yongyouSyncSaleStore,
    getOrgList,
    getOtherOutStoreBillType,
    getUser,
    getStoreStockStatus,
    getOtherOutStoreReverseWriting,
    saveOtherOutStoreCfig,
    getYongyouCustomerType,
    getCustomerCfig,
    saveCustomerType,
    syncyongyouStore,
    syncStoreStock,
    getOtherStoreCfig,
    selecUser,
    outStoreTypePageSelect,
    saveOtherStoreCfig,
    saveyongyouSyncOtherStore,
    syncyongyouOtherStore,
    saveNetworkTypeCfig,
    getYongyouNetworkType,
    saveSyncNetwork,
    syncNetwork,
    syncCode,
  } from '@/api/application'
  import { brandPageSelect, typePageSelect } from '@/api/goodsInfo'
  import errCode from '@/config/err-code'
  import {
    Collection,
    Hide,
    Iphone,
    MapLocation,
    PriceTag,
    Refresh,
    SoldOut,
    Tickets,
    View,
  } from '@element-plus/icons-vue'
  import routeComponentName from '@/config/route-component-name'
  import DateRange from '@/components/business/date-range/DateRange.vue'
  import {
    ElForm,
    ElFormItem,
    ElSwitch,
    ElSelect,
    ElOption,
    ElIcon,
    ElProgress,
    ElInput,
    ElTree,
    ElCheckbox,
    ElTooltip,
    ElSpace,
    ElTable,
    ElTableColumn,
    ElEmpty,
    ElTabs,
    ElTabPane,
  } from 'element-plus'
  import {
    useGetSaleWarehouseOutSet,
    useSaveYongYouSaleWarehouseOutSet,
    useSaveYongYouSaleWarehouseOutSetAndAsync,
  } from '@/services/pages/application/useYongYou'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const {
    set: saleWarehouseOutGetSetVal,
    getSetLoading: getSaleWarehouseOutSetLoading,
    getSet: getSaleWarehouseOutSet,
  } = useGetSaleWarehouseOutSet()
  const {
    saveSetVal: saleWarehouseOutSaveSetVal,
    saveSetLoading: saleWarehouseOutSetSaveSetLoading,
    saveSet: saleWarehouseOutSetSaveSet,
  } = useSaveYongYouSaleWarehouseOutSet()
  const {
    saveSetAndAsyncVal: saleWarehouseOutSaveSetAndAsyncVal,
    saveSetAndAsyncLoading: saleWarehouseOutSaveSetAndAsyncLoading,
    saveSetAndAsync: saleWarehouseOutSaveSetAndAsync,
  } = useSaveYongYouSaleWarehouseOutSetAndAsync()

  defineOptions({
    name: routeComponentName.appCenter.kingdeeYongyouConnectConfig,
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  const tableDataList = ref([
    // { name: '公司信息接口', type: 1 },
    // { name: '网点信息接口', type: 12 },
    { name: '存货信息接口', type: 2 },
    { name: '条码信息接口', type: 23 },
    { name: '仓库信息接口', type: 3 },
    { name: '存货库存同步', type: 4 },
    { name: '其他出库单同步', type: 5 },
    { name: '销售出库单接口', type: 6 },
    // { name: '售后  物料出库单 >-其他出库单', type: 7 },
    // { name: '售后  结算付款单 >-用友  应付单', type: 8 },
    // { name: '售后  结算付款单 >-用友  应收单', type: 9 },
  ])
  /**
   * 单据状态：Z：暂存，A：保存，B：审核中，C：已审核
   */
  const orderStatus = ref([
    { name: '暂存', value: 'Z' },
    { name: '保存', value: 'A' },
    { name: '审核中', value: 'B' },
    { name: '已审核', value: 'C' },
  ])
  const goodsCfigVo = ref({
    goodsBrandId: '', //物料品牌ID
    goodsType: 1, //物料类型：1-成品，2-物料,示例值(1)
    goodsTypeId: '', //物料分类ID，没有则不同步
    goodsTypeVos: [],
    syncGoodsPrice: true, //是否同步物料价格：false-不同步，true-同步,示例值(true)
  })
  // 公司信息保存设置数据
  const userCfigVo = ref({
    customerAddress: '',
    customerArea: '',
    customerCity: '',
    customerPhone: '',
    customerProvince: '',
    customerTypeVos: [],
  })

  const YunxkStoreCfig = ref({
    storeAddress: '',
    storeArea: '',
    storeCity: '',
    storePhone: '', //仓库负责人手机号
    storeProvince: '',
    storeUsername: '', //仓库默认负责人姓名
    syncStoreStock: true, //是否同步库存：false-关闭，true-开启,示例值(true)
  })

  const storeCfigVo = ref({
    syncSaleOutStorePrice: true,
  })
  const is_show1 = ref(false)
  const is_show2 = ref(false)
  const is_show3 = ref(false)
  const is_show4 = ref(false)
  const is_show5 = ref(false)
  const is_edit1 = ref(false)
  const is_edit2 = ref(false)
  const is_edit3 = ref(false)
  const is_edit4 = ref(false)
  const is_edit5 = ref(false)
  // 弹窗显示
  const popRightDialog = ref(false)
  const popRightTitle = ref('') //弹窗标题
  const Description_Content = ref('') //描述
  const synchronous_Conditions = ref('') //同步条件
  const activeName = ref('first')
  const loading = ref(false)

  /**
   * 关闭同步弹窗
   */
  const onCloseSynchronizationDialog = () => {
    if (dataReturned.value && dataReturned.value.end) {
      dataReturned.value = null
      isBigAsync.value = false
      isMinAsync.value = false
    }
  }

  const maskString = (str) => {
    if (!str) return
    var start = str.slice(0, 4)
    var end = str.slice(-4)
    var masked = start + '*'.repeat(6) + end
    return masked
  }
  const handleClick = (tab) => {
    activeName.value = tab.paneName
    selectObj.value = {
      treeIds: [], //设置原本已有权限ID集合回显
      treeAllIds: [], //获取原本全部ID
      checkedArr: [], //获取子级半选中的父级ID
      isIndeterminate: false, //判断半选状态
      allIds: [],
      allValue: false, //全选
    }
    selectList.value = []
    goodsCfigVo.value.goodsTypeVos = []
    loading.value = true
    Promise.all([getGoodsCfigInfo(), getGoodsTypeListFun()]).then(() => {
      loading.value = false
    })
  }
  const isType = ref(0)

  const popRight = async (type) => {
    popRightDialog.value = true
    isType.value = type
    dataReturned.value = null
    msgHtml.value = []
    goodsList.value = []
    loading_goods.value = false
    closeWebSocket()
    isBigAsync.value = false
    isMinAsync.value = false
    switch (type) {
      case 1:
        userCfigVo.value = {
          customerAddress: '',
          customerArea: '',
          customerCity: '',
          customerPhone: '',
          customerProvince: '',
          customerTypeVos: [],
        }
        userSelectObj.value = {
          treeIds: [], //设置原本已有权限ID集合回显
          treeAllIds: [], //获取原本全部ID
          checkedArr: [], //获取子级半选中的父级ID
          isIndeterminate: false, //判断半选状态
          allIds: [],
          allValue: false, //全选
        }
        loading.value = true
        Promise.all([getYunxkUserCfigInfo(), getYongyouCustomerTypeFun()]).then(() => {
          loading.value = false
        })
        popRightTitle.value = '公司信息同步设置'
        Description_Content.value = '用友公司资料 → 售后系统公司档案'
        synchronous_Conditions.value = '公司状态为已启用的'
        break
      case 12:
        networkCfigVo.value = {
          networkAddress: '',
          networkArea: '',
          networkCity: '',
          networkPhone: '',
          networkProvince: '',
          networkTown: '',
          networkTypeVo: [],
        }
        networkSelectObj.value = {
          treeIds: [], //设置原本已有权限ID集合回显
          treeAllIds: [], //获取原本全部ID
          checkedArr: [], //获取子级半选中的父级ID
          isIndeterminate: false, //判断半选状态
          allIds: [],
          allValue: false, //全选
        }
        networkList.value = []
        loading.value = true
        Promise.all([getYongyouNetworkTypeFun()]).then(() => {
          loading.value = false
        })
        popRightTitle.value = '网点信息同步设置'
        Description_Content.value = '用友网点资料 → 售后系统网点档案'
        synchronous_Conditions.value = '网点状态为已启用的'
        break
      case 2:
        goodsCfigVo.value = {
          goodsBrandId: '', //物料品牌ID
          goodsType: 1, //物料类型：1-成品，2-物料,示例值(1)
          goodsTypeId: '', //物料分类ID，没有则不同步
          goodsTypeVos: [],
          syncGoodsPrice: true, //是否同步物料价格：false-不同步，true-同步,示例值(true)
        }
        selectObj.value = {
          treeIds: [], //设置原本已有权限ID集合回显
          treeAllIds: [], //获取原本全部ID
          checkedArr: [], //获取子级半选中的父级ID
          isIndeterminate: false, //判断半选状态
          allIds: [],
          allValue: false, //全选
        }
        selectList.value = []
        activeName.value = 'first'
        loading.value = true
        Promise.all([getGoodsCfigInfo(), getBrandOptions(''), getGoodsTypeListFun()]).then(() => {
          loading.value = false
        })
        popRightTitle.value = '存货信息同步设置'
        Description_Content.value = '用友物料资料 → 售后系统产品档案'
        synchronous_Conditions.value = '物料状态为已启用的'
        break
      case 3:
        loading.value = true
        await getYunxkStoreCfigInfo()
        loading.value = false
        popRightTitle.value = '仓库信息同步设置'
        Description_Content.value = '用友仓库 → 售后系统仓库管理'
        synchronous_Conditions.value = '仓库状态为已启用的'
        break
      case 4:
        break
      case 5:
        loading.value = true
        Promise.all([getOtherStoreCfigFun(), selecUserFun(), outStoreTypePageSelectFun()]).then(
          () => {
            loading.value = false
          },
        )
        popRightTitle.value = '其他出库单同步设置'
        Description_Content.value = '用友其他出库单 → 售后系统出库单'
        synchronous_Conditions.value = '单据是“已审核”的状态'
        break
      case 6:
        storeCfigVo.value.syncSaleOutStorePrice = true
        popRightTitle.value = '销售出库单同步设置'
        Description_Content.value = '用友销售出库单 → 售后系统出库单'
        synchronous_Conditions.value = '单据是“已审核”的状态'
        getSaleWarehouseOutSet().then(() => {
          saleWarehouseOutSaveSetVal.value = saleWarehouseOutGetSetVal.value
          saleWarehouseOutSaveSetAndAsyncVal.value = saleWarehouseOutGetSetVal.value
        })
        break
      case 7:
        loading.value = true
        Promise.all([
          getOtherOutStoreReverseWritingFun(),
          getOtherOutStoreBillTypeFun(),
          getUserFun(),
          getStockOrgListFun(),
          getStoreStockStatusFun(),
        ]).then(() => {
          loading.value = false
        })
        popRightTitle.value = '物料出库单反写设置'
        Description_Content.value = '售后系统物料出库单→ 用友其他出库单'
        synchronous_Conditions.value = '单据是“已审核”的状态'
        break
      case 8:
        popRightTitle.value = '结算付款单反写设置'
        Description_Content.value = '售后系统付款单→ 用友其他付款单'
        synchronous_Conditions.value = '单据是“已审核”的状态'
        break
      case 9:
        popRightTitle.value = '结算收款单反写设置'
        Description_Content.value = '售后系统收款单→ 用友其他收款单'
        synchronous_Conditions.value = '单据是“已审核”的状态'
        break
    }
  }

  // 获取其他出库单的单据类型
  const OtherOutStoreBillType = ref([])
  const outStoreData = ref({
    number: '',
    name: '',
  })
  const getOtherOutStoreBillTypeFun = _.debounce(() => {
    getOtherOutStoreBillType(outStoreData.value).then((res) => {
      if (res.data.code == 20000) {
        OtherOutStoreBillType.value = res.data.data.rows
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }, 200)
  const getStockOrgListOp = ref([])
  const getStockOrgListFun = async () => {
    await getOrgList().then((res) => {
      if (res.data.code == 20000) {
        getStockOrgListOp.value = res.data.data.rows.map((o) => {
          o.stockOrgId = JSON.stringify(o.stockOrgId)
          return o
        })
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }
  // 公司数据
  const getUserObj = ref([])
  const getUserData = ref({
    number: '',
    name: '',
  })
  const getUserFun = () => {
    getUser(getUserData.value).then((res) => {
      if (res.data.code == 20000) {
        getUserObj.value = res.data.data.rows.map((o) => {
          o.id = JSON.stringify(o.id)
          return o
        })
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }
  const reverseWritingCfigVo = ref({
    otherStoreBillStatus: 'Z', //反写用友其他出库单的单据状态：Z：暂存，A：保存，B：审核中，C：已审核,示例值(A)
    otherStoreBillType: '', //反写用友其他出库单单据类型名称
    otherStoreBillTypeId: '', //反写用友其他出库单单据类型ID
    otherStoreBillTypeNumber: '', //反写用友其他出库单单据类型条码
    otherStoreCust: '', //反写用友其他出库单的公司名称
    otherStoreCustId: '', //反写用友其他出库单的公司ID
    otherStoreCustNumber: '', //反写用友其他出库单的公司条码
    otherStoreStockStatus: '', //反写用友其他出库单的库存状态名称
    otherStoreStockStatusId: '', //反写用友其他出库单的库存状态ID
    otherStoreStockStatusNumber: '', //反写用友其他出库单的库存状态条码
    syncOtherStoreGoodsPrice: true, //是否同步反写用友其他出库单价格：false-关闭，true-开启,示例值(true)
    // "stockOrgId": "",
    // "stockOrgName": "",
    // "stockOrgNumber": "",
  })
  const getOtherOutStoreReverseWritingFun = async () => {
    await getOtherOutStoreReverseWriting().then((res) => {
      if (res.data.code == 20000) {
        reverseWritingCfigVo.value = res.data.data.row
        reverseWritingCfigVo.value.otherStoreBillStatus =
          res.data.data.row.otherStoreBillStatus || 'Z'
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }
  // 库存状态
  const getStoreStockStatusObj = ref([])
  const getStoreStockStatusFun = () => {
    getStoreStockStatus().then((res) => {
      if (res.data.code == 20000) {
        getStoreStockStatusObj.value = res.data.data.rows.map((o) => {
          o.id = JSON.stringify(o.id)
          return o
        })
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }

  //*************************获取用友其他出库单配置 */
  const OtherStoreCfig = ref({
    otherOutCustomerId: '', //同步其他出库单默认补充收货公司ID
    otherOutStoreTypeId: '', //同步其他出库单默认补充单据类型ID
  })
  const getOtherStoreCfigFun = () => {
    getOtherStoreCfig().then((res) => {
      if (res.data.code == 20000) {
        OtherStoreCfig.value = res.data.data.row
        if (OtherStoreCfig.value.otherOutCustomerId == '0') {
          OtherStoreCfig.value.otherOutCustomerId = ''
        }
        if (OtherStoreCfig.value.otherOutStoreTypeId == '0') {
          OtherStoreCfig.value.otherOutStoreTypeId = ''
        }
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }
  /***************其他出库公司下拉**************/
  const dataUserObj = ref({
    limit: 0,
    name: '',
    page: 0,
  })
  const dataUserList = ref([])
  const selecUserFun = _.debounce(() => {
    selecUser(dataUserObj.value).then((res) => {
      if (res.data.code == 20000) {
        dataUserList.value = res.data.data.rows
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }, 500)
  /***********其他出库单据类型***********/
  const outStoreTypeObj = ref({
    limit: 0,
    name: '',
    page: 0,
  })
  const outStoreTypeList = ref([])
  const outStoreTypePageSelectFun = _.debounce(() => {
    outStoreTypePageSelect(outStoreTypeObj.value).then((res) => {
      if (res.data.code == 20000) {
        outStoreTypeList.value = res.data.data.rows
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }, 500)
  // 判断是否可操作
  const ctrlShow = ref(false)
  /**
   * 获取用友配置信息
   */
  const getYunxkCfigObj = ref({
    appKey: '',
    appSecret: '',
    fromAccount: '',
    toAccount: '',
    enabled: true,
    url: '',
  })
  const getYunxkCfigInfo = async () => {
    await getYongyouSetCfig().then((res) => {
      if (res.data.code == 20000) {
        getYunxkCfigObj.value = res.data.data.row
        ctrlShow.value = res.data.data.row.enabled
        if (!res.data.data.row.enabled) {
          is_show1.value = false
          is_edit1.value = false
          is_show2.value = false
          is_edit2.value = false
          is_show3.value = false
          is_edit3.value = false
          is_show4.value = false
          is_edit4.value = false
          is_show5.value = false
          is_edit5.value = false
        }
        if (!getYunxkCfigObj.value.fromAccount) {
          is_show1.value = true
          is_edit1.value = true
        }
        if (!getYunxkCfigObj.value.toAccount) {
          is_show4.value = true
          is_edit4.value = true
        }
        if (!getYunxkCfigObj.value.appKey) {
          is_show2.value = true
          is_edit2.value = true
        }
        if (!getYunxkCfigObj.value.appSecret) {
          is_show3.value = true
          is_edit3.value = true
        }
        if (!getYunxkCfigObj.value.url) {
          is_show5.value = true
          is_edit5.value = true
        }
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }
  // 产品品牌下拉相关
  const brandOptions = ref([])
  const brandLoad = ref(false)
  const brandVal = ref('')
  // 获取产品品牌下拉
  const getBrandOptions = async (name) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    await brandPageSelect(data).then((res) => {
      brandOptions.value = res.data.data.rows
    })
  }
  // 搜索产品品牌下拉
  const searchBrandSelect = (query) => {
    brandVal.value = query
    if (query) {
      brandLoad.value = true
      setTimeout(async () => {
        brandLoad.value = false
      }, 1000)
    }
  }
  watch(
    () => brandVal.value,
    (newVal) => {
      if (newVal != '') {
        getBrandOptions(newVal)
      } else {
        getBrandOptions('')
      }
    },
  )
  // 搜索产品分类下拉
  const typeVal = ref('')
  const goodsList = ref([])
  const total = ref(0)
  const loading_goods = ref(false)
  // **********获取全部物料*********
  const selectList: any = ref([])

  // 获取产品失败提示，用在界面显示，提醒用户
  const errMsgForGetGoodTypeFail = ref('')

  /**
   * 获取产品分类
   */
  const getGoodsTypeListFun = async () => {
    const res = await getyongyouGoodsTypeList(activeName.value == 'first' ? 1 : 2)
    if (res.data.code === 20000) {
      selectList.value = res.data.data.rows.map((o) => {
        if (o.childData.length == 0) {
          delete o.childData
        } else {
          o.childData = setStatus(o.childData)
        }
        if (!o.disabled) {
          selectObj.value.allIds.push(o.code)
        }

        return o
      })

      nextTick(() => {
        // ****设置选中*****
        treeRef.value!.setCheckedKeys(selectObj.value.treeIds, false)
        handleCheckChange()
      })
    } else {
      errMsgForGetGoodTypeFail.value = res.data.message
      if (errCode.applicationErrCode.yongyou[res.data.code]) {
        errMsgForGetGoodTypeFail.value = errCode.applicationErrCode.yongyou[res.data.code]
      }
    }
  }

  function setStatus(arr) {
    return arr.map((o) => {
      if (!o.disabled) {
        selectObj.value.allIds.push(o.code)
      }
      if (o.childData && o.childData.length > 0) {
        setStatus(o.childData)
      }
      return o
    })
  }
  // ****获取选中的节点2******
  const getCheckedNodes = () => {
    goodsCfigVo.value.goodsTypeVos = []
    for (let index = 0; index < selectList.value.length; index++) {
      const item = selectList.value[index]
      if (selectObj.value.checkedArr.includes(item.code)) {
        let authorVosItem = {
          parentTypeId: 0, //父级权限菜单ID
          type: item.name,
          typeId: item.code,
          childData: [],
        }
        authorVosItem.childData = getChilrenArr(item.childData, item.code)
        goodsCfigVo.value.goodsTypeVos.push(authorVosItem)
      }
    }
  }
  function getChilrenArr(arr, code) {
    let arr2 = arr.filter((o) => selectObj.value.checkedArr.includes(o.code))
    return arr2.map((o) => {
      let authorVosItem = {
        typeId: o.code,
        childData: [],
        type: o.name,
        parentTypeId: code, //父级权限菜单ID
      }
      if (o.childData && o.childData.length > 0) {
        authorVosItem.childData = getChilrenArr(o.childData, o.code)
      }
      return authorVosItem
    })
  }
  // ***2全选****
  const changeAll = (val) => {
    if (val) {
      nextTick(() => {
        treeRef.value!.setCheckedKeys(selectObj.value.allIds, false)
        handleCheckChange()
      })
    } else {
      treeRef.value!.setCheckedKeys([], false)
    }
    selectObj.value.isIndeterminate = false
  }

  const treeRef = ref()
  // 已勾选的ID集合
  // 列表勾选变化
  const handleCheckChange = () => {
    let parentArr = treeRef.value!.getHalfCheckedKeys(false, false)
    selectObj.value.checkedArr = treeRef.value!.getCheckedKeys(false, false)
    selectObj.value.checkedArr.push(...parentArr)
    selectObj.value.allValue = selectObj.value.checkedArr.length == selectObj.value.allIds.length
    selectObj.value.isIndeterminate =
      selectObj.value.checkedArr.length > 0 &&
      selectObj.value.checkedArr.length < selectObj.value.allIds.length
  }

  //*********************************公司******************* */
  const treeUserRef = ref()
  const userSelectObjchangeAll = (val) => {
    if (val) {
      nextTick(() => {
        treeUserRef.value!.setCheckedKeys(userSelectObj.value.allIds, false)
        userSelectObjhandleCheckChange()
      })
    } else {
      treeUserRef.value!.setCheckedKeys([], false)
    }
    userSelectObj.value.isIndeterminate = false
  }

  // 已勾选的ID集合
  // 列表勾选变化
  const userSelectObjhandleCheckChange = () => {
    let parentArr = treeUserRef.value!.getHalfCheckedKeys(false, false)
    userSelectObj.value.checkedArr = treeUserRef.value!.getCheckedKeys(false, false)
    userSelectObj.value.checkedArr.push(...parentArr)
    userSelectObj.value.allValue =
      userSelectObj.value.checkedArr.length == userSelectObj.value.allIds.length
    userSelectObj.value.isIndeterminate =
      userSelectObj.value.checkedArr.length > 0 &&
      userSelectObj.value.checkedArr.length < userSelectObj.value.allIds.length
  }
  // ****获取选中的节点1******
  const getUserCheckedNodes = () => {
    userCfigVo.value.customerTypeVos = []
    for (let index = 0; index < goodsList.value.length; index++) {
      const item = goodsList.value[index]
      if (userSelectObj.value.checkedArr.includes(item.code)) {
        let authorVosItem = {
          parentTypeId: 0, //父级权限菜单ID
          type: item.name,
          typeId: item.code,
          childData: [],
        }
        authorVosItem.childData = getUserChilrenArr(item.childData, item.code)
        userCfigVo.value.customerTypeVos.push(authorVosItem)
      }
    }
  }
  function getUserChilrenArr(arr, code) {
    let arr2 = arr.filter((o) => userSelectObj.value.checkedArr.includes(o.code))
    return arr2.map((o) => {
      let authorVosItem = {
        typeId: o.code,
        childData: [],
        type: o.name,
        parentTypeId: code, //父级权限菜单ID
      }
      if (o.childData && o.childData.length > 0) {
        authorVosItem.childData = getUserChilrenArr(o.childData, o.code)
      }
      return authorVosItem
    })
  }
  /**
   * 获取用友公司配置
   */
  const getYunxkUserCfigInfo = async () => {
    await getCustomerCfig().then((res) => {
      if (res.data.code == 20000) {
        userCfigVo.value = res.data.data.row
        address.value = {
          province: userCfigVo.value.customerProvince,
          city: userCfigVo.value.customerCity,
          area: userCfigVo.value.customerArea,
          town: '',
        }
        userSelectObj.value.treeIds = []
        userSelectObj.value.treeAllIds = []
        goodsCfigVo.value.goodsTypeVos.map((o) => {
          userSelectObj.value.treeAllIds.push(o.typeId)
          getUserIds(o.childData, o.typeId)
        })
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }
  function getUserIds(arr, typeId) {
    if (arr.length == 0) {
      userSelectObj.value.treeIds.push(typeId)
    } else {
      arr.map((o) => {
        userSelectObj.value.treeAllIds.push(o.typeId)
        getIds(o.childData, o.typeId)
      })
    }
  }
  // 1
  const userSelectObj = ref({
    treeIds: [], //设置原本已有权限ID集合回显
    treeAllIds: [], //获取原本全部ID
    checkedArr: [], //获取子级半选中的父级ID
    isIndeterminate: false, //判断半选状态
    allIds: [],
    allValue: false, //全选
  })
  // 公司分类
  const getYongyouCustomerTypeFun = async () => {
    await getYongyouCustomerType().then((res) => {
      if (res.data.code == 20000) {
        goodsList.value = res.data.data.rows
        total.value = Number(res.data.data.total)
        goodsList.value = res.data.data.rows.map((o) => {
          if (o.childData.length == 0) {
            delete o.childData
          } else {
            o.childData = setUserStatus(o.childData)
          }
          if (!o.disabled) {
            userSelectObj.value.allIds.push(o.code)
          }
          return o
        })
        nextTick(() => {
          // ****设置选中*****
          treeUserRef.value!.setCheckedKeys(userSelectObj.value.treeIds, false)
          userSelectObjhandleCheckChange()
        })
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }
  function setUserStatus(arr) {
    return arr.map((o) => {
      if (!o.disabled) {
        userSelectObj.value.allIds.push(o.code)
      }
      if (o.childData && o.childData.length > 0) {
        setUserStatus(o.childData)
      }
      return o
    })
  }
  const address = ref({
    province: '',
    city: '',
    area: '',
    town: '',
  })
  const singleAddressRef = ref()

  const defaultProps = {
    children: 'childData',
    label: 'name',
    disabled: 'disabled',
  }
  /*************************************12网点*********************************** */
  const networkSelectObj = ref({
    treeIds: [], //设置原本已有权限ID集合回显
    treeAllIds: [], //获取原本全部ID
    checkedArr: [], //获取子级半选中的父级ID
    isIndeterminate: false, //判断半选状态
    allIds: [],
    allValue: false, //全选
  })
  // 网点信息保存同步数据
  const networkCfigVo = ref({
    networkAddress: '',
    networkArea: '',
    networkCity: '',
    networkPhone: '',
    networkProvince: '',
    networkTown: '',
    networkTypeVo: [],
  })
  const networkList = ref([])
  const getYongyouNetworkTypeFun = () => {
    getYongyouNetworkType().then((res) => {
      if (res.data.code == 20000) {
        networkList.value = res.data.data.rows
        networkList.value = res.data.data.rows.map((o) => {
          if (o.childData.length == 0) {
            delete o.childData
          } else {
            o.childData = setNetworkStatus(o.childData)
          }
          if (!o.disabled) {
            networkSelectObj.value.allIds.push(o.code)
          }
          return o
        })
        nextTick(() => {
          // ****设置选中*****
          treeUserRef.value!.setCheckedKeys(networkSelectObj.value.treeIds, false)
          networkSelectObjhandleCheckChange()
        })
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }
  function setNetworkStatus(arr) {
    return arr.map((o) => {
      if (!o.disabled) {
        networkSelectObj.value.allIds.push(o.code)
      }
      if (o.childData && o.childData.length > 0) {
        setNetworkStatus(o.childData)
      }
      return o
    })
  }
  const networkSelectObjchangeAll = (val) => {
    if (val) {
      nextTick(() => {
        treeUserRef.value!.setCheckedKeys(networkSelectObj.value.allIds, false)
        networkSelectObjhandleCheckChange()
      })
    } else {
      treeUserRef.value!.setCheckedKeys([], false)
    }
    networkSelectObj.value.isIndeterminate = false
  }

  // 已勾选的ID集合
  // 列表勾选变化
  const networkSelectObjhandleCheckChange = () => {
    let parentArr = treeUserRef.value!.getHalfCheckedKeys(false, false)
    networkSelectObj.value.checkedArr = treeUserRef.value!.getCheckedKeys(false, false)
    networkSelectObj.value.checkedArr.push(...parentArr)
    networkSelectObj.value.allValue =
      networkSelectObj.value.checkedArr.length == networkSelectObj.value.allIds.length
    networkSelectObj.value.isIndeterminate =
      networkSelectObj.value.checkedArr.length > 0 &&
      networkSelectObj.value.checkedArr.length < networkSelectObj.value.allIds.length
  }
  // ****获取选中的节点1******
  const getNetworkCheckedNodes = () => {
    networkCfigVo.value.networkTypeVo = []
    for (let index = 0; index < networkList.value.length; index++) {
      const item = networkList.value[index]
      if (networkSelectObj.value.checkedArr.includes(item.code)) {
        let authorVosItem = {
          parentTypeId: 0, //父级权限菜单ID
          type: item.name,
          typeId: item.code,
          childData: [],
        }
        authorVosItem.childData = getNetworkChilrenArr(item.childData, item.code)
        networkCfigVo.value.networkTypeVo.push(authorVosItem)
      }
    }
  }
  function getNetworkChilrenArr(arr, code) {
    let arr2 = arr.filter((o) => networkSelectObj.value.checkedArr.includes(o.code))
    return arr2.map((o) => {
      let authorVosItem = {
        typeId: o.code,
        childData: [],
        type: o.name,
        parentTypeId: code, //父级权限菜单ID
      }
      if (o.childData && o.childData.length > 0) {
        authorVosItem.childData = getNetworkChilrenArr(o.childData, o.code)
      }
      return authorVosItem
    })
  }

  /**************************************end************************************** */
  // 2
  const selectObj = ref({
    treeIds: [], //设置原本已有权限ID集合回显
    treeAllIds: [], //获取原本全部ID
    checkedArr: [], //获取子级半选中的父级ID
    isIndeterminate: false, //判断半选状态
    allIds: [],
    allValue: false, //全选
  })
  const getGoodsCfigInfo = async () => {
    await getyongyouGoodsCfig(activeName.value == 'first' ? 1 : 2).then((res) => {
      if (res.data.code == 20000) {
        goodsCfigVo.value = res.data.data.row
        goodsCfigVo.value['goodsBrandId'] = res.data.data.row.goodsBrandId
          ? res.data.data.row.goodsBrandId
          : ''
        selectObj.value.treeIds = []
        selectObj.value.treeAllIds = []
        goodsCfigVo.value.goodsTypeVos.map((o) => {
          selectObj.value.treeAllIds.push(o.typeId)
          getIds(o.childData, o.typeId)
        })
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }
  function getIds(arr, typeId) {
    if (arr.length == 0) {
      selectObj.value.treeIds.push(typeId)
    } else {
      arr.map((o) => {
        selectObj.value.treeAllIds.push(o.typeId)
        getIds(o.childData, o.typeId)
      })
    }
  }
  // 3
  const getYunxkStoreCfigInfo = async () => {
    await getYongyouStoreCfig().then((res) => {
      if (res.data.code == 20000) {
        YunxkStoreCfig.value = res.data.data.row
        address.value = {
          province: YunxkStoreCfig.value.storeProvince,
          city: YunxkStoreCfig.value.storeCity,
          area: YunxkStoreCfig.value.storeArea,
          town: '',
        }
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }
  // 保存设置
  const saveCommit = async () => {
    loading.value = true
    isMinAsync.value = false
    switch (isType.value) {
      case 1:
        var { province, city, area } = singleAddressRef.value.getSelectAddr()
        userCfigVo.value.customerProvince = province
        userCfigVo.value.customerCity = city
        userCfigVo.value.customerArea = area
        getUserCheckedNodes()
        saveCustomerType(userCfigVo.value).then((res) => {
          if (res.data.code == 20000) {
            onPopCancel()
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          } else {
            ElMessage({
              message: res.data.message,
              type: 'error',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          }
          loading.value = false
        })
        break
      case 12:
        var { province, city, area } = singleAddressRef.value.getSelectAddr()
        networkCfigVo.value.networkProvince = province
        networkCfigVo.value.networkCity = city
        networkCfigVo.value.networkArea = area
        getNetworkCheckedNodes()
        saveNetworkTypeCfig(networkCfigVo.value).then((res) => {
          if (res.data.code == 20000) {
            onPopCancel()
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          } else {
            ElMessage({
              message: res.data.message,
              type: 'error',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          }
          loading.value = false
        })
        break
      case 2:
        getCheckedNodes()
        goodsCfigVo.value.goodsType = activeName.value == 'first' ? 1 : 2
        saveyongyouGoodsCfig(goodsCfigVo.value).then((res) => {
          if (res.data.code == 20000) {
            onPopCancel()
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          } else {
            ElMessage({
              message: res.data.message,
              type: 'error',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          }
          loading.value = false
        })
        break
      case 3:
        var { province, city, area } = singleAddressRef.value.getSelectAddr()
        YunxkStoreCfig.value.storeProvince = province
        YunxkStoreCfig.value.storeCity = city
        YunxkStoreCfig.value.storeArea = area
        saveYongyouStoreCfig(YunxkStoreCfig.value).then((res) => {
          if (res.data.code == 20000) {
            onPopCancel()
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          } else {
            ElMessage({
              message: res.data.message,
              type: 'error',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          }
          loading.value = false
        })
        break
      case 4:
        break
      case 5:
        saveOtherStoreCfig(OtherStoreCfig.value).then((res) => {
          if (res.data.code == 20000) {
            onPopCancel()
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          } else {
            ElMessage({
              message: res.data.message,
              type: 'error',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          }
          loading.value = false
        })
        break
      case 6:
        onSaveSaleWarehouseOutSet()
        break
      case 7:
        saveOtherOutStoreCfig(reverseWritingCfigVo.value).then((res) => {
          if (res.data.code == 20000) {
            getUserData.value = {
              name: '',
              number: '',
            }
            onPopCancel()
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          } else {
            ElMessage({
              message: res.data.message,
              type: 'error',
              duration: 5000,
              plain: true,
              showClose: true,
            })
          }
          loading.value = false
        })
        break
      case 8:
        break
      case 9:
        break
    }
  }

  /**
   * 销售出库单保存事件
   */
  const onSaveSaleWarehouseOutSet = async () => {
    const warehouseOutSetSaveRes = await saleWarehouseOutSetSaveSet()
    if (warehouseOutSetSaveRes.code === 20000) {
      loading.value = false
      HMessage.success('保存设置成功')
      onPopCancel()
      return
    }
    HMessageBox.error(warehouseOutSetSaveRes.message)
  }

  /**
   * 销售出库单起止日期更新事件
   * @param {Object} val - 返回的参数
   * @param {String} val.startDate - 开始日期
   * @param {String} val.endDate - 结束日期
   */
  const handleSaleWarehouseOutStartAndEndDateChange = (val: {
    startDate: string
    endDate: string
  }) => {
    if (val.startDate && val.endDate) {
      saleWarehouseOutSaveSetVal.value.saleStoreBillStartDate = val.startDate
      saleWarehouseOutSaveSetVal.value.saleStoreBillEndDate = val.endDate
    }
  }

  const typeOptions = ref([])
  // 获取产品分类下拉
  const getTypeOptions = async (name) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    await typePageSelect(data).then((res) => {
      typeOptions.value = res.data.data.rows
    })
  }
  watch(
    () => typeVal.value,
    (newVal) => {
      if (newVal != '') {
        getTypeOptions(newVal)
      } else {
        getTypeOptions('')
      }
    },
  )

  // 同步进度
  const syncProgress = ref(0)

  // 进度同步定时器
  const syncProgressTimer = ref<NodeJS.Timeout | null>(null)

  /**
   * 开启定时器（进度同步定时器）
   */
  const startSyncProgressTimer = () => {
    syncProgressTimer.value = setInterval(() => {
      syncProgress.value = Number((syncProgress.value + 0.01).toFixed(2))
      if (dataReturned.value && !dataReturned.value.end && syncProgress.value >= 99.99) {
        stopSyncProgressTimer()
      }
    }, 1000)
  }

  /**
   * 关闭定时器（进度同步定时器）
   */
  const stopSyncProgressTimer = () => {
    if (syncProgressTimer.value) {
      clearInterval(syncProgressTimer.value)
    }
  }

  /**
   * 获取WebSocket返回的数据
   * @param {object} msg - WebSocket返回的数据
   */
  const msgHtml = ref([])
  const funProgress = (msg) => {
    dataReturned.value = msg
    if (msg.message) {
      msgHtml.value.push(msg?.message)
    }
    if (msg.end) {
      stopSyncProgressTimer()
    }
    scrollHeight()
    scrollHeight2()
  }

  // 滚动到底部
  const msgContentBoxs = ref()
  const scrollHeight = () => {
    nextTick(() => {
      if (msgContentBoxs.value) {
        msgContentBoxs.value.scrollTop = msgContentBoxs.value.scrollHeight
      }
    })
  }
  const msgContentBoxs2 = ref()
  const scrollHeight2 = () => {
    nextTick(() => {
      if (msgContentBoxs2.value) {
        msgContentBoxs2.value.scrollTop = msgContentBoxs2.value.scrollHeight
      }
    })
  }

  // websocket返回的数据
  const dataReturned = ref()

  /**
   * 保存并同步
   */
  const saveAsyncCommit = async () => {
    syncProgress.value = 0
    dataReturned.value = null
    msgHtml.value = []
    let province = ''
    let city = ''
    let area = ''
    await nextTick(() => {
      if (singleAddressRef.value) {
        const address = singleAddressRef.value.getSelectAddr()
        province = address.province
        city = address.city
        area = address.area
      }
    })
    loading.value = true
    var uuid = new Date().getTime()
    initWebSocket(funProgress, `/ws/progress/${uuid}`)
    startSyncProgressTimer()
    let res: { code: number; message: string; data: object; success: boolean } | null = null
    switch (isType.value) {
      case 1:
        userCfigVo.value.customerProvince = province
        userCfigVo.value.customerCity = city
        userCfigVo.value.customerArea = area
        getUserCheckedNodes()
        res = (await saveSyncCustomerCfig(userCfigVo.value, uuid)).data
        break
      case 12:
        networkCfigVo.value.networkProvince = province
        networkCfigVo.value.networkCity = city
        networkCfigVo.value.networkArea = area
        getNetworkCheckedNodes()
        res = (await saveSyncNetwork(networkCfigVo.value, uuid)).data
        break
      case 2:
        getCheckedNodes()
        goodsCfigVo.value.goodsType = activeName.value == 'first' ? 1 : 2
        res = (await saveWithSyncGoods(goodsCfigVo.value, uuid)).data
        break
      case 3:
        YunxkStoreCfig.value.storeProvince = province
        YunxkStoreCfig.value.storeCity = city
        YunxkStoreCfig.value.storeArea = area
        res = (await saveSyncStor(YunxkStoreCfig.value, uuid)).data
        break
      case 4:
        break
      case 5:
        res = (await saveyongyouSyncOtherStore(OtherStoreCfig.value, uuid)).data
        break
      case 6:
        // res = (await saveSyncYunxkSaleStore(storeCfigVo.value, uuid)).data
        res = await saleWarehouseOutSaveSetAndAsync(uuid)
        break
      case 7:
        break
      case 8:
        break
      case 9:
        break
    }
    loading.value = false
    if (res) {
      if (res.code !== 20000) {
        ElMessageBox({
          title: '提示',
          message: errCode.applicationErrCode.yongyou[res.code] || res.message,
          type: 'error',
        })
        return
      }
      isMinAsync.value = true
    }
  }

  // 同步
  const loading_async = ref(false)
  const isBigAsync = ref(false)
  const isMinAsync = ref(false)
  const enableSynchronizationMsg = ref('')
  const asyncTypeShow = (type, goodsType = 1) => {
    ElMessageBox.confirm('确定同步此操作？', '提示', {
      confirmButtonText: '确定',
      type: 'warning',
      async beforeClose(action, instance, done) {
        if (['cancel', 'close'].includes(action)) {
          done()
        }

        if (action === 'confirm') {
          syncProgress.value = 0
          dataReturned.value = null
          msgHtml.value = []
          const uuid = new Date().getTime()
          initWebSocket(funProgress, `/ws/progress/${uuid}`)
          startSyncProgressTimer()
          instance.cancelButtonLoading = true
          instance.confirmButtonLoading = true
          let res: { code: number; message: string; success: boolean; data: object } | null = null
          switch (type) {
            case 1:
              res = (await syncCustomer(uuid)).data
              break
            case 12:
              res = (await syncNetwork(uuid)).data
              break
            case 2:
              res = (await saveyongyouSyncGoods(goodsType, uuid)).data
              break
            case 23:
              res = (await syncCode(uuid)).data
              break
            case 3:
              res = (await syncyongyouStore(uuid)).data
              break
            case 4:
              res = (await syncStoreStock(uuid)).data
              break
            case 5:
              res = (await syncyongyouOtherStore(uuid)).data
              break
            case 6:
              res = (await yongyouSyncSaleStore(uuid)).data
              break
            case 7:
              break
            case 8:
              break
            case 9:
              break
          }
          instance.cancelButtonLoading = false
          instance.confirmButtonLoading = false
          if (res) {
            done()
            if (res.code !== 20000) {
              ElMessageBox({
                type: 'error',
                title: '提示',
                message: errCode.applicationErrCode.yongyou[res.code] || res.message,
              })
              return
            }
            errCode.applicationErrCode.yongyou[res.code] || res.message
            if (errCode.applicationErrCode.yongyou[res.code]) {
              enableSynchronizationMsg.value = errCode.applicationErrCode.yongyou[res.code]
            }
            isBigAsync.value = true
          }
        }
      },
    })
  }

  // 保存用友配置
  const changeacctId = _.debounce(() => {
    setYongyouSave(getYunxkCfigObj.value).then((res) => {
      if (res.data.code == 20000) {
        getYunxkCfigInfo()
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      }
    })
  }, 300)

  // 关闭弹窗
  const onPopCancel = () => {
    popRightDialog.value = false
    dataReturned.value = null
    msgHtml.value = []
  }
  onMounted(() => {
    loading_async.value = true
    Promise.all([getYunxkCfigInfo()]).then(() => {
      loading_async.value = false
    })
  })
  // 编辑点击
  const editShow = (val) => {
    is_show1.value = false
    is_edit1.value = false
    is_edit2.value = false
    is_show2.value = false
    is_edit3.value = false
    is_show3.value = false
    is_edit4.value = false
    is_show4.value = false
    is_edit5.value = false
    is_show5.value = false
    switch (val) {
      case 1:
        is_show1.value = true
        is_edit1.value = true
        break
      case 2:
        is_edit2.value = true
        is_show2.value = true
        break
      case 3:
        is_edit3.value = true
        is_show3.value = true
        break
      case 4:
        is_edit4.value = true
        is_show4.value = true
        break
      case 5:
        is_edit5.value = true
        is_show5.value = true
        break

      default:
        break
    }
  }
</script>

<style scoped lang="scss">
  @import './index';

  .goods_type {
    display: flex;
    flex-direction: column;
    flex: 1;
    padding: 0px 40px;
    overflow: hidden;

    &::-webkit-scrollbar-track {
      background: transparent; //背景颜色
    }

    &:hover {
      overflow: auto;
    }

    .no-data-wrapper {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;

      .main-tip {
        font-size: 20px;
        text-align: center;
        display: flex;
        margin: 48px 0;
        column-gap: 5px;
        align-items: center;

        .iconfont {
          display: block;
          width: 32px;
          height: 32px;
          border-radius: 32px;
          background-color: $deleteColor;
          color: #fff;
          line-height: 32px;
          text-align: center;
          font-size: 24px;
        }

        .txt {
          line-height: 32px;
        }
      }

      .sub-tip {
        color: #777;
        font-size: 16px;
      }
    }
  }
</style>
